//
//  DCAlbumViewController.swift
//  HoneyBee
//
//  Created by point on 2018/6/10.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import Photos

private let DCCustomAlbumViewCellID = "DCCustomAlbumViewCellID"
private let maxSelected = 3 //选择的最大值

class DCAlbumViewController: BaseViewController {
    var currentMax = 0 //已经选择了几个
    var selectImgArr:[DCAlbumModel] = [DCAlbumModel]() //数组模型
    var transmissionImgArr:[UIImage] = [UIImage]() //选择好的
    typealias funcBlock = (_ result : [UIImage]) -> ()
    var blockImageArr : funcBlock?
    
    var col:CGFloat = 3 //默认3列
    var margin:CGFloat = 10 //边距
    var itemWidth: CGFloat = 0
    ///取得的资源结果，用了存放的PHAsset
    var assetsFetchResults:PHFetchResult<AnyObject>!
    var fetchResults:PHFetchResult<AnyObject>!
    ///缩略图大小
    var assetGridThumbnailSize:CGSize!
    /// 带缓存的图片管理对象
    var imageManager:PHCachingImageManager!
    
    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.sectionInset = UIEdgeInsets(top: margin, left:margin , bottom: margin, right: margin)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: LayoutCommon.navHeight, width: LayoutCommon.width, height: LayoutCommon.height - LayoutCommon.navHeight), collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(DCCustomAlbumCollectionViewCell.self, forCellWithReuseIdentifier: DCCustomAlbumViewCellID)
        collectionView.isPagingEnabled = false
        collectionView.bounces = true
        collectionView.scrollsToTop = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = UIColor.white
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        DispatchQueue.main.async(execute: {
            self.collectionView.reloadData()
        })
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
    
}


// MARK: - 交互
extension DCAlbumViewController {
    @objc func clickSubmit()  {
        
        transmissionImgArr.removeAll()
        for model  in selectImgArr {
            guard let modelImg = model.img  else { continue }
            transmissionImgArr.append(modelImg)
        }
        if (blockImageArr != nil) {
            self.blockImageArr!(transmissionImgArr)
        }
        self.navigationController?.popViewController(animated: true)
    }
    
}

extension DCAlbumViewController:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  self.assetsFetchResults!.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DCCustomAlbumViewCellID, for: indexPath) as!DCCustomAlbumCollectionViewCell
        let asset = self.assetsFetchResults?[indexPath.row] as! PHAsset
        
        self.imageManager.requestImage(for: asset, targetSize: assetGridThumbnailSize, contentMode:  PHImageContentMode.aspectFill, options: nil) { (img, info) in
            cell.img.image = img
        }
        cell.configModel(modelArr: selectImgArr, index: indexPath)
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let model = selectImgArr[indexPath.item]
        if !model.selected { //控制最大数选择
            var tempImgArr:[UIImage] = [UIImage]()
            for model  in selectImgArr {
                guard let modelImg = model.img  else { continue }
                tempImgArr.append(modelImg)
            }
            
            if  maxSelected - currentMax - tempImgArr.count < 0{
                self.hudLoadMessage("你只能选择\(maxSelected)张")
                return
            }
        }
        model.selected = !model.selected
        
        if  model.selected {
            let asset = self.assetsFetchResults?[indexPath.row] as! PHAsset
            let options = PHImageRequestOptions()
            options.isNetworkAccessAllowed = true
            options.isSynchronous = true
            options.resizeMode = .fast
            options.deliveryMode = .fastFormat
            PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .default, options: options) { (img, info) in
                guard let img = img else { model.img = nil ; return }
                model.img = img
            }
        }else {
            model.img = nil
        }
        self.collectionView.reloadItems(at: [IndexPath(item: indexPath.item, section: 0)])
    }
}

extension DCAlbumViewController {
    fileprivate func setupUI(){
        title = "图片选择"
        itemWidth = CGFloat(Int((kScreenW - (margin * (col + 1))) / col))
        assetGridThumbnailSize = CGSize(width: itemWidth, height: itemWidth)
      
        setupPhoto()
        view.backgroundColor = UIColor.white
        view.addSubview(collectionView)
        let item = UIBarButtonItem(title: "确定", style: UIBarButtonItem.Style.plain, target: self, action: #selector(clickSubmit))
        item.tintColor = UIColor.white
        self.navItem.rightBarButtonItem=item
    }
    
    
    func myReload() {
        setupPhoto()
        self.collectionView.reloadData()
    }
    
    func setupPhoto() {
        //则获取所有资源
        let allPhotosOptions = PHFetchOptions()
        //按照创建时间倒序排列
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                             ascending: false)]
        //只获取图片
        allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
        let fetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: allPhotosOptions)
        self.assetsFetchResults = fetchResults as! PHFetchResult <AnyObject>
        
        for _ in 0...assetsFetchResults.count  {
            self.selectImgArr.append(DCAlbumModel())
        }
        
        
        // 初始化和重置缓存
        self.imageManager = PHCachingImageManager()
        self.resetCachedAssets()
        
    
    }
    
    //重置缓存
    func resetCachedAssets(){
        self.imageManager.stopCachingImagesForAllAssets()
    }
}
